package com.mypage.view.activity.beautMore;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.cloudcc.mobile.R;
import com.cloudcc.mobile.entity.beau.BeauInfoEntity;
import com.cloudcc.mobile.manager.RunTimeManager;
import com.cloudcc.mobile.manager.UrlManager;
import com.cloudcc.mobile.view.activity.BeauInfoActivity;
import com.cloudcc.mobile.view.base.BaseActivity;
import com.google.gson.Gson;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.litesuits.android.async.Log;
import com.mypage.bean.ConvertState;
import com.mypage.utils.AnimViewUtils;
import com.mypage.utils.SaveTemporaryData;
import com.mypage.utils.UtilsShowDialog;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class ConvertCustomersActivity extends BaseActivity {

    @Bind(R.id.btnSeclete)
    Button btnSeclete;
    @Bind(R.id.btnContent)
    Button btnContent;
    public String mEns = RunTimeManager.getInstance().getlanguage();
    @Bind(R.id.btnCancel)
    Button btnCancel;
    @Bind(R.id.btnYes)
    Button btnYes;
    @Bind(R.id.imgDele)
    ImageView imgDele;
    @Bind(R.id.btn_searchs)
    EditText btnSearchs;
    @Bind(R.id.etInput)
    EditText etInput;
    @Bind(R.id.toastHintContents)
    TextView toastHintContents;
    @Bind(R.id.imgDeletess)
    ImageView imgDeletess;
    @Bind(R.id.layoutBack)
    RelativeLayout layoutBack;
    @Bind(R.id.layoutTop)
    FrameLayout layoutTop;
    private UtilsShowDialog showDialog;
    private String mChange;
    private String mOwerName;
    private String mOwerId;
    private String objId;
    private String oppName;
    private String mEntityId;
    private List<BeauInfoEntity.ObjChange> mJot;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ButterKnife.bind(this);
        showDialog = new UtilsShowDialog(this);
        initData();
        initListener();
    }

    @Override
    protected void onResume() {
        super.onResume();
        stateTextColer();
    }

    public void initData() {
        stateData();
        CustomPermission();
        mJot = (List<BeauInfoEntity.ObjChange>) getIntent().getSerializableExtra("mBeauInfo.recordIdButton");
        objId = getIntent().getStringExtra("mEntityNameID");
        mEntityId = getIntent().getStringExtra("mEntityId");
        oppName = getIntent().getStringExtra("oppName");
//        if (mJot != null && !mJot.isEmpty()) {
//            if ("更改所有人".equals(mJot.get(0).buttonName) || "ChangeOwner".equals(mJot.get(0).buttonName)) {
//                mOwerName = mJot.get(0).ownerList.get(0).ownerccname;
//                mOwerId = mJot.get(0).ownerList.get(0).ownerid;
//                btnContent.setText(mOwerName);
//            }
//        }


        mOwerName = getIntent().getStringExtra("OwnerName");
        mOwerId = getIntent().getStringExtra("OwnerId");
        btnContent.setText(mOwerName);
        Permission();
    }

    private boolean isClick = false;
    private boolean isForeResule = false;
    public void initListener() {
        btnSearchs.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                // 输入的内容变化的监听
                Log.e("输入过程中执行该方法", "文字变化");

            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count,
                                          int after) {
                // 输入前的监听
                Log.e("输入前确认执行该方法", "开始输入");

            }

            @Override
            public void afterTextChanged(Editable s) {
                // 输入后的监听
                Log.e("输入结束执行该方法", "输入结束");
                if(isForeResule){
                    isForeResule = false;
                }else{
                    mCustomId = null;

                }
                if (s.length() != 0) {
                    isClick = true;
                    btnYes.setTextColor(android.graphics.Color.parseColor("#0C77D4"));
                    btnYes.setBackgroundResource(R.drawable.beau_btn_genghuan_shap);
                    stateTextColer();
                } else {
                    stateTextColer();
                    isClick = false;
                    btnYes.setTextColor(android.graphics.Color.parseColor("#C0CAD4"));
                    btnYes.setBackgroundResource(R.drawable.beau_btn_dark_genghuan_shap);
                }
                Permission();
            }
        });

    }

    @OnClick({R.id.btnSeclete, R.id.btnContent, R.id.btnCancel, R.id.btnYes, R.id.imgDele, R.id.imgSearch})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btnCancel:
                finish();
                break;
            case R.id.btnYes:
                if (isClick) {
                    quan();
                }
                break;
            case R.id.btnSeclete:
                Intent intent = new Intent(this, ConvertPupopActivity.class);//选着状态
                intent.putExtra("state", btnSeclete.getText().toString());
                startActivityForResult(intent, 2);
                break;
            case R.id.btnContent:
                start();
                break;
            case R.id.imgDele:
//                btnContent.setText("");
//                mOwerId = "";
                start();
                break;
            case R.id.imgSearch:
                cakan();
                break;
        }
    }
    public void cakan(){
        if (Querrys){

            jumpClient();

        }else{
            showToast("无查看客户列表权限");
        }
    }
    public void jumpClient() {
        Intent in = new Intent(this, ClientListActivity.class);
        in.putExtra("mObjId", objId);
        in.putExtra("accountModify", accountModify);
        startActivityForResult(in, 3);
    }

    public void start() {
        Intent intents = new Intent(this, ConvertPersionActivity.class);//记录所有人
        if ("en".equals(mEns)) {
            intents.putExtra("User", "Enter the new owner name");
        } else {
            intents.putExtra("User", "输入新所有人名称");
        }
        startActivityForResult(intents, 1);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (data == null)
            return;
        if (requestCode == 1) {//所有人
            mOwerName = data.getStringExtra("Name");
            mOwerId = data.getStringExtra("mId");

            btnContent.setText(mOwerName);

        } else if (requestCode == 2) {//对话框

            btnSeclete.setText(data.getStringExtra("mName"));
            setBacText();
        } else if (requestCode == 3) {//客户
            accountAdd = true;
            isForeResule = true;
            mCustomId = data.getStringExtra("mId");
            mCustomName = data.getStringExtra("mName");
            btnSearchs.setText(mCustomName);

        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    public String mCustomId = null;
    public String mCustomName;
    private List<ConvertState.State> mList;

    public void stateData() {
        HttpUtils utils = new HttpUtils();
        RequestParams params = new RequestParams();
        params.addBodyParameter("binding", RunTimeManager.getInstance().getServerBinding());
        params.addBodyParameter("serviceName", "getLeadConvertCode");


        utils.send(HttpRequest.HttpMethod.POST, UrlManager.getInterfaceUrl(), params, new RequestCallBack<String>() {

            @Override
            public void onFailure(HttpException arg0, String arg1) {
                // TODO Auto-generated method stub

            }

            @Override
            public void onSuccess(ResponseInfo<String> arg0) {
                // TODO Auto-generated method stub
//                parseData(arg0.result.toString());
                String s = arg0.result.toString();
                ConvertState convert = new Gson().fromJson(arg0.result.toString(), ConvertState.class);
                mList = convert.data;
                btnSeclete.setText(mList.get(0).codevalue);
                stateTextColer();
            }


        });
    }

    public void updataData() {
        showDialog.onShowLoadingDialog("正在加载...");
        String url = UrlManager.getInterfaceUrl();
        String b = RunTimeManager.getInstance().getServerBinding();
        HttpUtils utils = new HttpUtils();
        RequestParams params = new RequestParams();
        params.addBodyParameter("binding", RunTimeManager.getInstance().getServerBinding());
        params.addBodyParameter("serviceName", "saveLeadConvertCode");
        params.addBodyParameter("leadId", mEntityId);
        params.addBodyParameter("ownerId", mOwerId);
        if (mCustomId==null){
            params.addBodyParameter("accountId", "");
        }else{
            params.addBodyParameter("accountId", mCustomId);
        }
        params.addBodyParameter("accountName", btnSearchs.getText().toString());
        params.addBodyParameter("oppName", etInput.getText().toString());
        Log.d("---request转换---", url + "?binding=" + b + "&serviceName=saveLeadConvertCode&leadId=" + mEntityId + "&ownerId=" + mOwerId + "&accountId=" + mCustomId
                + "&accountName=" + btnSearchs.getText().toString() + "&oppName=" + etInput.getText().toString());



        utils.send(HttpRequest.HttpMethod.POST, UrlManager.getInterfaceUrl(), params, new RequestCallBack<String>() {

            @Override
            public void onFailure(HttpException arg0, String arg1) {
                // TODO Auto-generated method stub
                showDialog.onDismissLoadingDialog();
            }

            @Override
            public void onSuccess(ResponseInfo<String> arg0) {
                // TODO Auto-generated method stub
                parseData(arg0.result.toString());
            }


        });
    }

    public String beauId;

    private void parseData(String json) {
        showDialog.onDismissLoadingDialog();
        try {
            JSONObject obj = new JSONObject(json);

            boolean Fail = obj.getBoolean("result");
            String mToast = obj.getString("returnInfo");
            if (Fail) {

            } else {
                showToast(mToast);
                return;
            }


            beauId = obj.getJSONObject("data").getString("contactId");

            boolean b = obj.getBoolean("result");

            if (b) {
//                SaveTemporaryData.mToastStr = "保存业务成功";
                BeauInfoActivity.inatance.finish();
                jumpDetail();
                return;
            }
            Toast.makeText(this, "转换失败", Toast.LENGTH_SHORT).show();
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }


    public void jumpDetail() {
        SaveTemporaryData.NUMBER = 1;
        Intent intent = new Intent(mContext, BeauInfoActivity.class);
        intent.putExtra("beau.name", "联系人");
        intent.putExtra("beau.nameid", "contact");
        intent.putExtra("beau.imageid", "cloudtab_must_003");
        intent.putExtra("beau.ismefollow", false);
        SaveTemporaryData.converDetail = "concerSuccess";
        intent.putExtra("beau.id", beauId);
        intent.putExtra("OBJID", mOwerId);//获取对象的id
        intent.putExtra("OBJNAME", mOwerName);//获取对象的name


        intent.putExtra("beau.edit", false);
        startActivity(intent);

        finish();
//        this.overridePendingTransition(R.anim.zhuanchang, 0);
    }


    public void Permission() {
        HttpUtils utils = new HttpUtils();
        RequestParams params = new RequestParams();
        params.addBodyParameter("binding", RunTimeManager.getInstance().getServerBinding());
        params.addBodyParameter("serviceName", "checkLeadConvert");
        params.addBodyParameter("leadId", mEntityId);
        Log.d("----request UIR--", UrlManager.getInterfaceUrl() + "?binding=" + RunTimeManager.getInstance().getServerBinding() + "&serviceName=checkLeadConvert&leadId=" + mEntityId);
        utils.send(HttpRequest.HttpMethod.POST, UrlManager.getInterfaceUrl(), params, new RequestCallBack<String>() {

            @Override
            public void onFailure(HttpException arg0, String arg1) {
                // TODO Auto-generated method stub

            }

            @Override
            public void onSuccess(ResponseInfo<String> arg0) {
                // TODO Auto-generated method stub
                parse(arg0.result.toString());
            }
        });
    }


    private boolean allPermission;  //所有权限：如果为true,即为拥有所有权限
    private boolean accountAdd;    //客户新建权限
    private boolean accountModify = true; //客户编辑权限
    private boolean contactAdd;    //联系人新建权限
    private boolean contactroleAdd;//业务机会联系人角色新建权限
    private boolean opportunityAdd;//业务机会新建权限

    public void parse(String jsion) {
        try {
            JSONObject Obj = new JSONObject(jsion);
            allPermission = Obj.getJSONObject("data").getBoolean("allPermission");
            accountAdd = Obj.getJSONObject("data").getBoolean("accountAdd");
            accountModify = Obj.getJSONObject("data").getBoolean("accountModify");
            contactAdd = Obj.getJSONObject("data").getBoolean("contactAdd");
            contactroleAdd = Obj.getJSONObject("data").getBoolean("contactroleAdd");
            opportunityAdd = Obj.getJSONObject("data").getBoolean("opportunityAdd");
            if (allPermission) {
                accountModify = true;
            }

        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    private void quan() {
        if (allPermission) {
            updataData();
            return;
        }
        showDialog.onDismissLoadingDialog();
        if (accountAdd) {//有新建权限
            if ("".equals(btnSearchs.getText().toString())) {
                showToast("客户不能为空");
                return;
            }
        } else {//无新建权限

            if (mCustomId!=null){
                updataData();
                return;
            }

            if (!"".equals(btnSearchs.getText().toString())) {
                showToast("无新建客户权限");
                return;
            }

        }

        if (!contactroleAdd) {

            if (!"".equals(etInput.getText().toString())) {
                showToast("无业务机会联系人角色新建权限");
                return;
            }

        }

        if (!opportunityAdd) {

            if (!"".equals(etInput.getText().toString())) {
                showToast("无新建业务机会权限");
                return;
            }
        }


        if (!contactAdd) {
            showToast("无新建联系人权限");
            return;
        }


    if (mCustomId!=null){
        if (!accountModify){
                 showToast("无编辑客户权限");
                 return;
             }
    }

//        if ("".equals(mCustomId)||mCustomId==null){
//             if (!accountModify){
//                 showToast("无编辑客户权限");
//                 return;
//             }
//        }
        updataData();
    }


    @Override
    public int getLayoutId() {
        return R.layout.activity_convert_customers;
    }

    @OnClick(R.id.imgDeletess)
    public void onClick() {
        layoutTop.setVisibility(View.GONE);
    }

    public void showToast(String str) {
        layoutBack.setBackground(getResources().getDrawable(R.drawable.toast_hint));
        layoutTop.setVisibility(View.VISIBLE);
        layoutBack.setVisibility(View.GONE);
        toastHintContents.setText(str);
        new AnimViewUtils().appearToast(layoutBack);
    }

    private boolean isHave = false;

    public void stateTextColer() {

        if ("".equals(btnSearchs.getText().toString()))
            return;
        if (btnSeclete.getText().toString().contains("无")||btnSeclete.getText().toString().contains("No")) {
            setBacText();
            return;
        }


        if (btnSeclete.getText().toString().contains("无")||btnSeclete.getText().toString().contains("No")) {
            isClick = false;
            btnYes.setTextColor(android.graphics.Color.parseColor("#C0CAD4"));
            btnYes.setBackgroundResource(R.drawable.beau_btn_dark_genghuan_shap);
        } else {
            isClick = true;
            btnYes.setTextColor(android.graphics.Color.parseColor("#0C77D4"));
            btnYes.setBackgroundResource(R.drawable.beau_btn_genghuan_shap);
        }
    }

    public void setBacText() {
        isClick = false;
        btnYes.setTextColor(android.graphics.Color.parseColor("#C0CAD4"));
        btnYes.setBackgroundResource(R.drawable.beau_btn_dark_genghuan_shap);
    }

    public void CustomPermission() {
        showDialog.onShowLoadingDialog("正在加载...");
        String url = UrlManager.getInterfaceUrl();
        String b = RunTimeManager.getInstance().getServerBinding();
        HttpUtils utils = new HttpUtils();
        RequestParams params = new RequestParams();
        params.addBodyParameter("binding", RunTimeManager.getInstance().getServerBinding());
        params.addBodyParameter("serviceName", "getObjectPermissionByPrefix");
        params.addBodyParameter("prefix", "001");
        Log.d("---request客户权限--", url + "?binding=" + b + "&serviceName=getObjectPermissionByPrefix&prefix=001");

        utils.send(HttpRequest.HttpMethod.POST, UrlManager.getInterfaceUrl(), params, new RequestCallBack<String>() {

            @Override
            public void onFailure(HttpException arg0, String arg1) {
                // TODO Auto-generated method stub
                showDialog.onDismissLoadingDialog();
            }

            @Override
            public void onSuccess(ResponseInfo<String> arg0) {
                // TODO Auto-generated method stub
                showDialog.onDismissLoadingDialog();
                Log.d("ddddd", arg0.result.toString());
                Querry(arg0.result.toString());
            }


        });
    }
    private boolean Querrys = false;
    public void Querry(String s){
        try {
            JSONObject Obj = new JSONObject(s);
            Querrys = Obj.getJSONObject("data").getBoolean("query");

        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
}
